package com.junyu.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.junyu.interceptor.ThreadLocalUtil;
import com.junyu.mapper.LogMapper;
import com.junyu.pojo.entity.LoginLog;
import com.junyu.pojo.entity.User;
import com.junyu.pojo.vo.LoginStatistics;
import com.junyu.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

/**
 *日志接口实现类
 */
@Service
public class LogServiceImpl extends ServiceImpl<LogMapper, LoginLog> implements LogService {
    @Autowired
    private LogMapper logMapper;

    /**
     * 保存日志
     * @param loginLog 登录日志对象
     */
    @Override
    public void saveLog(LoginLog loginLog) {
        this.logMapper.insert(loginLog);
    }


    /**
     * 查询上一次登录日志
     * @param userName 用户名
     * @return LoginLog 登录日志对象
     */
    @Override
    public LoginLog findLogByUserName(String userName) {
        List<LoginLog> list = this.list(new LambdaQueryWrapper<LoginLog>().eq(LoginLog::getOperator, userName).orderByAsc(LoginLog::getCreateTime).last("limit 1"));
        if (CollectionUtil.isEmpty(list)) {
            return null;
        }
        return list.get(0);
    }


    /**
     * 近七日登录人次
     * @return List<LoginStatistics> 登陆人次统计列表
     */
    @Override
    public List<LoginStatistics> loginCount() {
        User user = ThreadLocalUtil.get();
        return this.logMapper.loginCount(user.getUserName());
    }
}
